//
//  DTBizMapPOISearch.m
//  PersonalManager
//
//  Created by user on 16/8/11.
//  Copyright © 2016年 Haiyun.Qian. All rights reserved.
//

#import "DTBizMapPOISearch.h"
#import <MAMapKit/MAMapKit.h>
#import <AMapSearchKit/AMapSearchAPI.h>
#import <AMapSearchKit/AMapSearchObj.h>
#import <AMapFoundationKit/AMapFoundationKit.h>

#define APIKey @"69c6f0fb1342fd18e767177c0453421f"
//30.129395    120.082408
@interface DTBizMapPOISearch ()<MAMapViewDelegate, AMapSearchDelegate,UITableViewDelegate,UITableViewDataSource>
{
    MAMapView     *_mapView;
    AMapSearchAPI *_search;
    
    AMapPOIAroundSearchRequest *mapPOIRequest;
    UITableView   *_tableView;
    NSArray       *_pois;
    
    CLLocation    *_currentLocation;
    UIButton      *_locationButton;
    
    NSString      *_tittle;
    AMapReGeocode *responses;
    
    //annotation
    NSMutableArray *_annotations;
}

@property (nonatomic, strong) NSString *keywords;
@property (nonatomic, strong) AMapGeoPoint *location;
@property (nonatomic) NSInteger *radius;


@end

@implementation DTBizMapPOISearch

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initMapView];
    
    [self initSearch];
    
    [self initControls];
    
    [self initLocationSetButton];
    
    [_mapView setZoomLevel:14.5];
    
    [_mapView setUserTrackingMode:MAUserTrackingModeFollow animated:YES];
    
    [self initTableView];
    
    [self initAnnotation];
}

#pragma mark - init

- (void)initMapView{
    
    [AMapServices sharedServices].apiKey = APIKey;
    _mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds) / 2 + 80)];
    
    _mapView.delegate = self;
    _mapView.compassOrigin = CGPointMake(_mapView.compassOrigin.x, 22);
    _mapView.scaleOrigin = CGPointMake(_mapView.scaleOrigin.x, 22);
    
    [self.view addSubview:_mapView];
    _mapView.showsUserLocation = YES;
}

- (void)initSearch
{
    _search = [[AMapSearchAPI alloc] init];
    _search.delegate = self;
    
}

- (void)initControls
{
    //定位按钮
    _locationButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _locationButton.frame = CGRectMake(20, CGRectGetHeight(_mapView.bounds) - 80, 40, 40);
    _locationButton.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin;
    _locationButton.backgroundColor = [UIColor whiteColor];
    _locationButton.layer.cornerRadius = 5;
    
    [_locationButton addTarget:self action:@selector(locateAction) forControlEvents:UIControlEventTouchUpInside];
    
    [_locationButton setImage:[UIImage imageNamed:@"location_no"] forState:UIControlStateNormal];
    
    [_mapView addSubview:_locationButton];
    
}

- (void)initLocationSetButton{
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"确定"
                                                                             style:UIBarButtonItemStyleDone
                                                                            target:self
                                                                            action:@selector(completeButtonAction)];
}

- (void) initTableView {

    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetHeight(_mapView.bounds) - 40,CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds)) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
}

- (void) initAnnotation {
    _annotations = [[NSMutableArray alloc]init];
    _pois = nil;
}

#pragma mark - Action
//跳转回到路线规划
- (void)completeButtonAction{
    
    [_command.controller.navigationController popViewControllerAnimated:true];
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"MapSearch",@"", nil];
    [_command successRessponse:dic];
}

- (void)locateAction
{
    if (_mapView.userTrackingMode != MAUserTrackingModeFollow)
    {
        [_mapView setUserTrackingMode:MAUserTrackingModeFollow animated:YES];
    }
    [self reGeoAction];
    
}

- (void) searchPOIAction {
    if (_currentLocation == nil || _search == nil) {
        return;
    }
    mapPOIRequest = [[AMapPOIAroundSearchRequest alloc]init];
    mapPOIRequest.location = [AMapGeoPoint locationWithLatitude:_currentLocation.coordinate.latitude longitude:_currentLocation.coordinate.longitude];
    mapPOIRequest.keywords = @"餐饮";

    [_search AMapPOIAroundSearch:mapPOIRequest];
}


#pragma mark - UITableViewDataSource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath
                                                                               *)indexPath
{
    static NSString *cellIdentifier = @"cellIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
                                      reuseIdentifier:cellIdentifier];
    }
    AMapPOI *poi = _pois[indexPath.row];
    cell.textLabel.text = poi.name;

    cell.detailTextLabel.text = poi.address;
    return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _pois.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.0001;
}

#pragma mark - UITableViewDelegate 

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    //清空标注 Annotation
    [_mapView removeAnnotations:_annotations];
    [_annotations removeAllObjects];

    [tableView deselectRowAtIndexPath:indexPath animated:true];
    
    AMapPOI *poi = _pois[indexPath.row];
    MAPointAnnotation *annotation = [[MAPointAnnotation alloc]init];
    
    annotation.coordinate = CLLocationCoordinate2DMake(poi.location.latitude, poi.location.longitude);
    annotation.title      = poi.name;
    annotation.subtitle   = poi.address;
    [_mapView addAnnotation:annotation];
    
    [_annotations addObject:annotation];
    [_mapView setCenterCoordinate:annotation.coordinate];
    
}
//设置annotation的相关属性
-(MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation {
    if ([annotation isKindOfClass:[MAPointAnnotation class]]) {
        static NSString *reuserID = @"AnnotationIdentifier";
        
        MAPinAnnotationView *annotationView = (MAPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuserID];
        if (annotationView == nil) {
            annotationView = [[MAPinAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:reuserID];
        }
        annotationView.canShowCallout = YES;
        return annotationView;
    }
    return nil;
}

#pragma mark -AMapPOIAroundSearchDelegate
//搜索回调
-(void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response {
    NSLog(@"request: %@", request);
    NSLog(@"response: %@", response);
    if (response.pois.count > 0)
    {
        _pois = response.pois;
        [_tableView reloadData];
        
    }
}

- (void)reGeoAction
{
    if (_currentLocation)
    {
        AMapReGeocodeSearchRequest *request = [[AMapReGeocodeSearchRequest alloc] init];
        request.location = [AMapGeoPoint locationWithLatitude:_currentLocation.coordinate.latitude
                                                    longitude:_currentLocation.coordinate.longitude];
        [_search AMapReGoecodeSearch:request];
    }
}


#pragma mark - AMapSearchDelegate

- (void)searchRequest:(id)request didFailWithError:(NSError *)error
{
    NSLog(@"request :%@, error :%@", request, error);
}
- (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response
{
    NSLog(@"response :%@", response);
    NSString *title = response.regeocode.addressComponent.city;
    if (title.length == 0)
    {
        title = response.regeocode.addressComponent.province;
    }
    _mapView.userLocation.title = title;
    _mapView.userLocation.subtitle = response.regeocode.formattedAddress;
}
#pragma mark - MAMapViewDelegate

- (void)mapView:(MAMapView *)mapView didChangeUserTrackingMode:(MAUserTrackingMode)mode animated:(BOOL)animated
{
    // 修改定位按钮状态
    if (mode == MAUserTrackingModeNone)
    {
        [_locationButton setImage:[UIImage imageNamed:@"location_no"] forState:UIControlStateNormal];
    }
    else
    {
        [_locationButton setImage:[UIImage imageNamed:@"location_yes"] forState:UIControlStateNormal];
    }
}

- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation
{
    _currentLocation = [userLocation.location copy];
    [self searchPOIAction];
}

- (void)mapView:(MAMapView *)mapView didSelectAnnotationView:(MAAnnotationView *)view
{
    // 选中定位annotation的时候进行逆地理编码查询
    if ([view.annotation isKindOfClass:[MAUserLocation class]])
    {
        [self reGeoAction];
    }
}
//地图发生移动后 调用此方法
//- (void) mapView:(MAMapView *)mapView regionDidChangeAnimated:(BOOL)animated{
//    //    [self Regeocode];
//    //    NSLog(@"地图中心店位置（%f,%f）",mapView.centerCoordinate.latitude,mapView.centerCoordinate.longitude);
//}
@end

